package cn.com.gas.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.common.config.FileUploadProperties;
import cn.com.common.constants.Constants;
import cn.com.gas.constants.GasConstants;
import cn.com.gas.entity.GasCamchangeEntity;
import cn.com.gas.entity.GasCamonlinetimeEntity;
import cn.com.gas.entity.GasOfflineCamEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStaytimeEntity;
import cn.com.gas.mapper.GasCamchangeMapper;
import cn.com.gas.mapper.GasCamonlinetimeMapper;
import cn.com.gas.mapper.GasStationinfoMapper;
import cn.com.gas.mapper.GasStaytimeMapper;
import cn.com.gas.service.GasOfflineCamService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeService;
import cn.com.nr.entity.NrCalculateEntity;
import cn.com.nr.entity.NrCamchangeEntity;
import cn.com.nr.entity.NrCamonlinetimeEntity;
import cn.com.nr.entity.NrConcreteEndangerEntity;
import cn.com.nr.entity.NrDiggingsEndangerEntity;
import cn.com.nr.entity.NrOfflineCamEntity;
import cn.com.nr.entity.NrRecordsEntity;
import cn.com.nr.entity.NrRecordsRe1Entity;
import cn.com.nr.entity.NrRecordsRe2Entity;
import cn.com.nr.mapper.NrCamchangeMapper;
import cn.com.nr.mapper.NrRecordsMapper;
import cn.com.nr.mapper.NrRecordsRe1Mapper;
import cn.com.nr.mapper.NrRecordsRe2Mapper;
import cn.com.nr.service.NrCalculateService;
import cn.com.nr.service.NrCamonlinetimeService;
import cn.com.nr.service.NrConcreteEndangerService;
import cn.com.nr.service.NrDiggingsEndangerService;
import cn.com.nr.service.NrOfflineCamService;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.SysParameterService;
import cn.com.thirdparty.entity.ProvinceGasCamQualityEntity;
import cn.com.thirdparty.entity.ZnGasCamera;
import cn.com.thirdparty.entity.ZnGasStation;
import cn.com.thirdparty.mapper.GasCameraWarningSqlMapper;
import cn.com.thirdparty.mapper.GasDetectionSqlMapper;
import cn.com.thirdparty.mapper.ProvinceGasCamQualityMapper;
import cn.com.thirdparty.mapper.ZnGasCameraMapper;
import cn.com.thirdparty.mapper.ZnGasStationMapper;
import cn.com.util.DateUtils;
import cn.com.util.TsBqUtils;
import lombok.extern.slf4j.Slf4j;

@Service("gasStaytimeService")
@Slf4j
public class GasStaytimeServiceImpl extends ServiceImpl<GasStaytimeMapper, GasStaytimeEntity>
		implements GasStaytimeService {

	@Autowired
	private GasStaytimeMapper gasStaytimeMapper;
	@Autowired
	private GasCamonlinetimeMapper gasCamonlinetimeMapper;
	@Autowired
	private NrCamonlinetimeService nrCamonlinetimeService;
	@Autowired
	private GasCamchangeMapper gasCamchangeMapper;
	@Autowired
	private NrCamchangeMapper nrCamchangeMapper;

	@Autowired
	private GasStationinfoMapper gasStationinfoMapper;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private FileUploadProperties fileUploadProperties;
	@Autowired
	private GasOfflineCamService gasOfflineCamService;
	@Autowired
	private NrOfflineCamService nrOfflineCamService;
	@Autowired
	private GasDetectionSqlMapper gasDetectionSqlMapper;
	@Autowired
	private SysParameterService sysParameterService;
	@Autowired
	private ZnGasStationMapper znGasStationMapper;
	@Autowired
	private ZnGasCameraMapper znGasCameraMapper;
	@Autowired
	private NrRecordsMapper nrRecordsMapper;
	@Autowired
	private NrRecordsRe1Mapper nrRecordsRe1Mapper;
	@Autowired
	private NrRecordsRe2Mapper nrRecordsRe2Mapper;
	
	@Autowired
	private NrDiggingsEndangerService nrDiggingsEndangerService;

	@Autowired
	private NrConcreteEndangerService nrConcreteEndangerService;

	@Autowired
	private NrCalculateService nrCalculateService;

	@Autowired
	private GasCameraWarningSqlMapper gasCameraWarningSqlMapper;
	@Autowired
	private ProvinceGasCamQualityMapper provinceGasCamQualityMapper;

	// @Transactional
	@Override
	public void asynSave(String payload) {

		if (TsBqUtils.isNotNull(payload)) {
			JSONObject jsonObject = JSON.parseObject(payload);
			String from = String.valueOf(jsonObject.get("from"));
			String time = String.valueOf(jsonObject.get("time"));

			JSONArray messageArray = JSONArray.parseArray(String.valueOf(jsonObject.get("message")));

			JSONObject messageObject = JSON.parseObject(String.valueOf(messageArray.get(0)));
			String msegType = String.valueOf(messageObject.get("msegType"));

			if (msegType.equals("9205")) {
				// 摄像头 在线离线处理
				gasCamonlinetimeSave(from, time, messageArray);
			} else if (msegType.equals("9207")) {
				// 摄像头 变动
				String image = String.valueOf(jsonObject.get("image"));
				gasCamChangeSave(from, time, messageArray, image);
			} else if (msegType.equals("9206") || msegType.equals("9208")) {
				// NR 自然资源 矿山 混凝土 等
				String image = String.valueOf(jsonObject.get("image"));
				nrRecordsSave(from, time, messageArray, image);

			} else {
				String image = String.valueOf(jsonObject.get("image"));
				String image1 = String.valueOf(jsonObject.get("image1"));
				gasGasStaytimeSave(from, time, image, image1, messageArray);

			}
		}
	}

	// NR 自然资源 矿山 混凝土 等
	private void nrRecordsSave(String from, String time, JSONArray messageArray, String image) {
		log.info("nrRecordsSave保存自然资源矿山、混凝土等:" + from);

		for (Object object : messageArray) {
			JSONObject messageObject = JSON.parseObject(String.valueOf(object));

			String msegType = String.valueOf(messageObject.get("msegType"));
			String camid = String.valueOf(messageObject.get("camid"));
			String channel = String.valueOf(messageObject.get("channel"));
			String areaNumber = String.valueOf(messageObject.get("areaNumber"));
			String areaName = String.valueOf(messageObject.get("areaName"));
			String ruleid = String.valueOf(messageObject.get("ruleId"));
			String ruleName = String.valueOf(messageObject.get("ruleName")); // 升降机、转轮、水泥车、运煤车
			String duration = String.valueOf(messageObject.get("duration"));
			String prob = String.valueOf(messageObject.get("prob"));
			String label = String.valueOf(messageObject.get("label"));
			
			String appear = String.valueOf(messageObject.get("appear"));
			String disappear = String.valueOf(messageObject.get("disappear"));
			
			String base64Extension = TsBqUtils.getBase64Extension(image);

			if (TsBqUtils.isNotNull(base64Extension)) {
				String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
				String imgName = TsBqUtils.getUUID();

				String path = fileUploadProperties.getPath() + createTime + File.separator;
				String url = fileUploadProperties.getUrl() + File.separator + createTime + File.separator + imgName
						+ "." + base64Extension;

				if (TsBqUtils.decodeBase64ToImage(image, path, imgName + "." + base64Extension)) {
					NrRecordsEntity entity = new NrRecordsEntity();
					GasStationinfoEntity stationinfo = gasStationinfoService.getById(camid);
					String pid = "";
					String calculate = "";
					if (TsBqUtils.isNotNull(stationinfo)) {
						pid = stationinfo.getPid();
						NrCalculateEntity oreCollectEntity = nrCalculateService.getById("oreCollect"); // 采矿
						NrCalculateEntity oreSelectEntity = nrCalculateService.getById("oreSelect"); // 选矿
						NrCalculateEntity cementEntity = nrCalculateService.getById("cement"); // 水泥
						NrCalculateEntity concreteEntity = nrCalculateService.getById("concrete"); // 混凝土

						if (ruleName.equals("转轮")) {
							NrDiggingsEndangerEntity nrDiggingsEndangerEntity = nrDiggingsEndangerService.getById(pid);
							if (TsBqUtils.isNotNull(nrDiggingsEndangerEntity)) {
								String ton2 = nrDiggingsEndangerEntity.getTon2();
								if (TsBqUtils.isNotNull(ton2)) {
									calculate = ton2;
								} else {
									calculate = oreCollectEntity.getTon2();
								}
							} else {
								calculate = oreCollectEntity.getTon2();
							}

						} else if (ruleName.equals("升降机")) {
							NrDiggingsEndangerEntity nrDiggingsEndangerEntity = nrDiggingsEndangerService.getById(pid);
							if (TsBqUtils.isNotNull(nrDiggingsEndangerEntity)) {
								String ton3 = nrDiggingsEndangerEntity.getTon3();
								if (TsBqUtils.isNotNull(ton3)) {
									calculate = ton3;
								} else {
									calculate = oreCollectEntity.getTon3();
								}
							} else {
								calculate = oreCollectEntity.getTon3();
							}

						} else {
							// 是否 矿山车辆
							NrDiggingsEndangerEntity nrDiggingsEndangerEntity = nrDiggingsEndangerService.getById(pid);
							if (TsBqUtils.isNotNull(nrDiggingsEndangerEntity)) {

								String industry = nrDiggingsEndangerEntity.getIndustry();
								String ton1 = nrDiggingsEndangerEntity.getTon1();
								if (TsBqUtils.isNotNull(ton1)) {
									calculate = ton1;
								} else {
									if (TsBqUtils.isNotNull(industry)) {
										if (industry.equals("铁矿采矿")) {
											calculate = oreCollectEntity.getTon1();
										} else if (industry.equals("铁矿选矿")) {
											calculate = oreSelectEntity.getTon1();
										}
									}
								}
							}

							// 是否 水泥 混凝土车辆
							NrConcreteEndangerEntity concreteEndangerEntity = nrConcreteEndangerService.getById(pid);
							if (TsBqUtils.isNotNull(concreteEndangerEntity)) {
								String industry = concreteEndangerEntity.getIndustry();
								String ton1 = concreteEndangerEntity.getTon1();
								if (TsBqUtils.isNotNull(ton1)) {
									calculate = ton1;
								} else {
									if (TsBqUtils.isNotNull(industry)) {
										if (industry.equals("水泥制造")) {
											calculate = cementEntity.getTon1();
										} else if (industry.equals("混凝土")) {
											calculate = concreteEntity.getTon1();
										}
									}
								}
							}
						}
					}
					
					entity.setFromTopic(from);
					
					// 重新设置日期
					if(from.contains("re")){
						// 重新执行数据
						entity.setTime(disappear);
					}else{
						// 增量数据
						entity.setTime(time);
					}
					
					entity.setMessageMsegtype(msegType);
					entity.setMessageCamid(camid);
					entity.setMessageChannel(channel);
					entity.setMessageAreanumber(areaNumber);
					entity.setMessageAreaname(areaName);
					entity.setMessageRuleid(ruleid);
					entity.setMessageRulename(ruleName); // 升降机、转轮、运煤车、水泥车
					entity.setMessageDuration(duration);
					entity.setMessageProb(prob);
					entity.setMessageLabel(label);
					
					entity.setMessageAppear(appear);
					entity.setMessageDisappear(disappear);
					
					entity.setImage(url);
					entity.setNrEndanger(pid);

					entity.setCalculate(calculate);
					
					entity.setDeleted(Constants.DELETEED_NOT);
					entity.setCreateTime(new Date());
					
					// 根据渠道进行分表
					if(from.contains("re2")){
						// 算法2
						NrRecordsRe2Entity entityRe2 = new NrRecordsRe2Entity();
						BeanUtils.copyProperties(entity, entityRe2);
						nrRecordsRe2Mapper.insert(entityRe2);
					}else if(from.contains("re1")||from.contains("re")){
						// 算法1
						NrRecordsRe1Entity entityRe1 = new NrRecordsRe1Entity();
						BeanUtils.copyProperties(entity, entityRe1);
						nrRecordsRe1Mapper.insert(entityRe1);
					}else{
						// 正常渠道
						nrRecordsMapper.insert(entity);
					}
					

				} else {
					log.info("decodeBase64ToImage图片处理失败");
				}
			} else {
				log.info("getBase64Extension文件后缀处理失败");
			}
		}
	}

	// 摄像头变动
	private void gasCamChangeSave(String from, String time, JSONArray messageArray, String image) {

		if (from.contains("mine")) {
			// 矿山变动
			log.info("矿山nrCamChangeSave保存摄像头变动:" + from);
			for (Object object : messageArray) {
				JSONObject messageObject = JSON.parseObject(String.valueOf(object));
				String msegType = String.valueOf(messageObject.get("msegType"));
				String camid = String.valueOf(messageObject.get("camid"));
				String groupid = String.valueOf(messageObject.get("groupid"));
				String base64Extension = TsBqUtils.getBase64Extension(image);

				if (TsBqUtils.isNotNull(base64Extension)) {
					String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
					String imgName = TsBqUtils.getUUID();

					String path = fileUploadProperties.getPath() + createTime + File.separator;
					String url = fileUploadProperties.getUrl() + File.separator + createTime + File.separator + imgName
							+ "." + base64Extension;

					if (TsBqUtils.decodeBase64ToImage(image, path, imgName + "." + base64Extension)) {
						NrCamchangeEntity entity = new NrCamchangeEntity();
						GasStationinfoEntity stationinfo = gasStationinfoService.getById(groupid);

						entity.setFromTopic(from);
						entity.setTime(time);
						entity.setMessageMsegtype(msegType);
						entity.setMessageCamid(camid);
						entity.setMessageGroupid(groupid);
						entity.setImage(url);
						entity.setDeleted(Constants.DELETEED_NOT);
						entity.setCreateTime(new Date());

						if (TsBqUtils.isNotNull(stationinfo)) {
							entity.setHandleTaxorgcode(stationinfo.getTaxorgcode());
						}
						nrCamchangeMapper.insert(entity);
					} else {
						log.info("decodeBase64ToImage图片处理失败");
					}
				} else {
					log.info("getBase64Extension文件后缀处理失败");
				}
			}

		} else {
			// 加油站变动
			log.info("加油gasCamChangeSave保存摄像头变动:" + from);

			for (Object object : messageArray) {
				JSONObject messageObject = JSON.parseObject(String.valueOf(object));
				String msegType = String.valueOf(messageObject.get("msegType"));
				String camid = String.valueOf(messageObject.get("camid"));
				String groupid = String.valueOf(messageObject.get("groupid"));
				String base64Extension = TsBqUtils.getBase64Extension(image);

				if (TsBqUtils.isNotNull(base64Extension)) {
					String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
					String imgName = TsBqUtils.getUUID();

					String path = fileUploadProperties.getPath() + createTime + File.separator;
					String url = fileUploadProperties.getUrl() + File.separator + createTime + File.separator + imgName
							+ "." + base64Extension;

					if (TsBqUtils.decodeBase64ToImage(image, path, imgName + "." + base64Extension)) {
						GasCamchangeEntity entity = new GasCamchangeEntity();
						GasStationinfoEntity stationinfo = gasStationinfoService.getById(groupid);

						entity.setFromTopic(from);
						entity.setTime(time);
						entity.setMessageMsegtype(msegType);
						entity.setMessageCamid(camid);
						entity.setMessageGroupid(groupid);
						entity.setImage(url);
						entity.setDeleted(Constants.DELETEED_NOT);
						entity.setCreateTime(new Date());

						if (TsBqUtils.isNotNull(stationinfo)) {
							entity.setHandleTaxorgcode(stationinfo.getTaxorgcode());
						}

						gasCamchangeMapper.insert(entity);

						try {
							SysParameterEntity parameterEntity102 = sysParameterService.getById("parameter102");
							if (TsBqUtils.isNotNull(parameterEntity102)) {
								String parameter102 = parameterEntity102.getParameter();
								if ("Y".equals(parameter102)) {

									GasStationinfoEntity groupidEntity = gasStationinfoService.getById(groupid);
									GasStationinfoEntity camidEntity = gasStationinfoService.getById(camid);
									String sql = "INSERT INTO gas_camera_warning(id, createtime, stationid, cameraid, indexcode, warningtype, waringimg, solvetype, solvemsg) "
											+ "VALUES ('" + TsBqUtils.getUUID() + "', '" + entity.getTime() + "', "
											+ groupidEntity.getThirdPartyId() + ", " + camidEntity.getThirdPartyId()
											+ ", 'indexcode', 'M', '" + entity.getImage() + "', '', '')";
									log.debug("执行sql:" + sql);
									gasCameraWarningSqlMapper.gasCameraWarningInsertInto(sql);

								}
							}
						} catch (Exception e) {
							log.info("INSERT INTO插入gas_camera_warning失败：" + e.getMessage());
						}

					} else {
						log.info("decodeBase64ToImage图片处理失败");
					}
				} else {
					log.info("getBase64Extension文件后缀处理失败");
				}
			}
		}
	}

	// 保存车流停留时间
	private void gasGasStaytimeSave(String from, String time, String image, String image1, JSONArray messageArray) {
		log.info("gasGasStaytimeSave保存车流停留时间:" + from);

		for (Object object : messageArray) {

			JSONObject messageObject = JSON.parseObject(String.valueOf(object));

			String msegType = String.valueOf(messageObject.get("msegType"));

			String channel = String.valueOf(messageObject.get("channel"));
			String areaNumber = String.valueOf(messageObject.get("areaNumber"));
			String areaName = String.valueOf(messageObject.get("areaName"));
			String ruleid = String.valueOf(messageObject.get("ruleId"));
			String ruleName = String.valueOf(messageObject.get("ruleName"));
			String prob = String.valueOf(messageObject.get("prob"));
			String appear = String.valueOf(messageObject.get("appear"));
			String disappear = String.valueOf(messageObject.get("disappear"));
			String label = String.valueOf(messageObject.get("label"));
			String plateNumber = String.valueOf(messageObject.get("plateNumber"));

			String camid = String.valueOf(messageObject.get("camid"));

			String regionCode = String.valueOf(messageObject.get("regionCode"));
			String deviceId = String.valueOf(messageObject.get("deviceId"));

			// String image = String.valueOf(jsonObject.get("image"));
			String base64Extension = TsBqUtils.getBase64Extension(image);

			if (TsBqUtils.isNotNull(regionCode) && TsBqUtils.isNotNull(deviceId)) {

				String base64Extension1 = TsBqUtils.getBase64Extension(image1);

				// 大模型逻辑
				if (TsBqUtils.isNotNull(base64Extension) && TsBqUtils.isNotNull(base64Extension1)) {
					String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
					String imgName = TsBqUtils.getUUID();
					String imgName1 = TsBqUtils.getUUID();

					String path = fileUploadProperties.getPath() + createTime + File.separator;

					String url = fileUploadProperties.getUrl() + File.separator + createTime + File.separator + imgName
							+ "." + base64Extension;
					String url1 = fileUploadProperties.getUrl() + File.separator + createTime + File.separator
							+ imgName1 + "." + base64Extension1;

					if (TsBqUtils.decodeBase64ToImage(image, path, imgName + "." + base64Extension)
							&& TsBqUtils.decodeBase64ToImage(image1, path, imgName1 + "." + base64Extension1)) {

						LambdaQueryWrapper<GasStaytimeEntity> queryWrapper = Wrappers.lambdaQuery();
						queryWrapper.eq(GasStaytimeEntity::getMessageLabel, label);
						queryWrapper.orderByAsc(GasStaytimeEntity::getTime);
						List<GasStaytimeEntity> list = this.list(queryWrapper);

						Date date = new Date();
						// TODO
						if (TsBqUtils.isNull(list)) {
							// 车辆进入
							GasStaytimeEntity gasStaytime = new GasStaytimeEntity();
							gasStaytime.setFromTopic(from.replaceAll("\\s", ""));
							gasStaytime.setTime(time);
							gasStaytime.setMessageMsegtype(msegType);

							gasStaytime.setMessageRuleid(ruleid);
							gasStaytime.setMessageRulename(ruleName);
							gasStaytime.setMessageProb(prob);
							gasStaytime.setMessageAppear(appear);
							gasStaytime.setMessageDisappear(disappear);

							// 新增字段
							gasStaytime.setField2(regionCode); // 加油站ID
							gasStaytime.setField3(deviceId); // 摄像机ID

							gasStaytime.setDeleted(Constants.DELETEED_NOT);
							gasStaytime.setImage(url);
							gasStaytime.setImage1(url1);

							gasStaytime.setCreateTime(date);
							this.save(gasStaytime);
						} else {
							// 车辆离开
							GasStaytimeEntity gasStaytimeEntity = list.get(0);
							gasStaytimeEntity.setMessageDisappear(disappear);
							gasStaytimeEntity.setImage1(url);
							gasStaytimeEntity.setUpdateTime(date);
							this.updateById(gasStaytimeEntity);
						}

					} else {
						log.info("decodeBase64ToImage图片处理失败");
					}

				} else {
					log.info("getBase64Extension文件后缀处理失败");
				}

			} else {
				// 其他逻辑
				if (TsBqUtils.isNotNull(base64Extension)) {
					String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
					String imgName = TsBqUtils.getUUID();

					String path = fileUploadProperties.getPath() + createTime + File.separator;
					String url = fileUploadProperties.getUrl() + File.separator + createTime + File.separator + imgName
							+ "." + base64Extension;

					if (TsBqUtils.decodeBase64ToImage(image, path, imgName + "." + base64Extension)) {
						// 查询已经存在GasStaytimeResult的label
						Date date = new Date();

						LambdaQueryWrapper<GasStaytimeEntity> queryWrapper = Wrappers.lambdaQuery();
						queryWrapper.eq(GasStaytimeEntity::getMessageLabel, label);
						queryWrapper.orderByAsc(GasStaytimeEntity::getTime);
						List<GasStaytimeEntity> list = this.list(queryWrapper);

						if (TsBqUtils.isNull(list)) {
							// 车辆进入
							GasStaytimeEntity gasStaytime = new GasStaytimeEntity();
							gasStaytime.setFromTopic(from.replaceAll("\\s", ""));
							gasStaytime.setTime(time);
							gasStaytime.setMessageMsegtype(msegType);
							gasStaytime.setMessageChannel(channel);
							gasStaytime.setMessageAreanumber(areaNumber);
							gasStaytime.setMessageAreaname(areaName);
							gasStaytime.setMessageRuleid(ruleid);
							gasStaytime.setMessageRulename(ruleName);
							gasStaytime.setMessageProb(prob);
							gasStaytime.setMessageAppear(appear);
							gasStaytime.setMessageDisappear(disappear);
							gasStaytime.setMessageLabel(label);

							gasStaytime.setField3(camid); // 摄像机ID

							gasStaytime.setMessagePlatennumber(plateNumber);

							gasStaytime.setDeleted(Constants.DELETEED_NOT);
							gasStaytime.setImage(url);

							gasStaytime.setCreateTime(date);
							this.save(gasStaytime);
						} else {
							// 车辆离开
							GasStaytimeEntity gasStaytimeEntity = list.get(0);

							if (TsBqUtils.isNotNull(disappear)) {
								gasStaytimeEntity.setMessageDisappear(disappear);
							}

							gasStaytimeEntity.setImage1(url);
							gasStaytimeEntity.setUpdateTime(date);
							this.updateById(gasStaytimeEntity);
						}

					} else {
						log.info("decodeBase64ToImage图片处理失败");
					}
				} else {
					log.info("getBase64Extension文件后缀处理失败");
				}
			}

		}

	}

	// 保存摄像头状态
	private void gasCamonlinetimeSave(String from, String time, JSONArray messageArray) {

		Date date = new Date();

		if (from.contains("mine")) {
			// 矿山离线
			log.info("gasCamonlinetimeSave保存矿山摄像头状态:" + from);

			for (Object object : messageArray) {

				NrCamonlinetimeEntity entity = new NrCamonlinetimeEntity();

				JSONObject parseObject = JSON.parseObject(String.valueOf(object));

				String msegType = String.valueOf(parseObject.get("msegType"));
				String camid = String.valueOf(parseObject.get("camid"));
				String disconnect = String.valueOf(parseObject.get("disconnect"));
				String connect = String.valueOf(parseObject.get("connect"));
				String label = String.valueOf(parseObject.get("label"));

				LambdaQueryWrapper<NrCamonlinetimeEntity> queryWrapper = Wrappers.lambdaQuery();
				queryWrapper.eq(NrCamonlinetimeEntity::getMessageLabel, label);
				queryWrapper.orderByAsc(NrCamonlinetimeEntity::getTime);
				List<NrCamonlinetimeEntity> list = nrCamonlinetimeService.list(queryWrapper);

				if (TsBqUtils.isNull(list)) {
					// 新增数据
					entity.setFromTopic(from);
					entity.setTime(time);
					entity.setMessageMsegtype(msegType);
					entity.setMessageCamid(camid);
					entity.setMessageDisconnect(disconnect);
					entity.setMessageConnect(connect);
					entity.setMessageLabel(label);
					entity.setCreateTime(date);
					entity.setDeleted(Constants.DELETEED_NOT);
					nrCamonlinetimeService.save(entity);
				} else {
					// 数据合并
					entity = list.get(0);
					entity.setMessageConnect(connect);
					entity.setUpdateTime(date);
					nrCamonlinetimeService.updateById(entity);

				}
				nrOfflineCamSaveAndUpdate(entity);
			}

		} else {
			log.info("gasCamonlinetimeSave保存加油站摄像头状态:" + from);
			for (Object object : messageArray) {

				GasCamonlinetimeEntity entity = new GasCamonlinetimeEntity();

				JSONObject parseObject = JSON.parseObject(String.valueOf(object));

				String msegType = String.valueOf(parseObject.get("msegType"));
				String camid = String.valueOf(parseObject.get("camid"));
				String disconnect = String.valueOf(parseObject.get("disconnect"));
				String connect = String.valueOf(parseObject.get("connect"));
				String label = String.valueOf(parseObject.get("label"));

				LambdaQueryWrapper<GasCamonlinetimeEntity> queryWrapper = Wrappers.lambdaQuery();
				queryWrapper.eq(GasCamonlinetimeEntity::getMessageLabel, label);
				queryWrapper.orderByAsc(GasCamonlinetimeEntity::getTime);
				List<GasCamonlinetimeEntity> list = gasCamonlinetimeMapper.selectList(queryWrapper);

				if (TsBqUtils.isNull(list)) {
					// 新增数据
					entity.setFromTopic(from);
					entity.setTime(time);
					entity.setMessageMsegtype(msegType);
					entity.setMessageCamid(camid);
					entity.setMessageDisconnect(disconnect);
					entity.setMessageConnect(connect);
					entity.setMessageLabel(label);
					entity.setCreateTime(date);
					entity.setDeleted(Constants.DELETEED_NOT);
					gasCamonlinetimeMapper.insert(entity);
				} else {
					// 数据合并
					entity = list.get(0);
					entity.setMessageConnect(connect);
					entity.setUpdateTime(date);
					gasCamonlinetimeMapper.updateById(entity);

				}
				gasOfflineCamSaveAndUpdate(entity);

			}
		}
	}

	private void gasOfflineCamSaveAndUpdate(GasCamonlinetimeEntity entity) {

		Date date = new Date();
		String camid = entity.getMessageCamid();
		String connect = entity.getMessageConnect();
		String disconnect = entity.getMessageDisconnect();

		GasStationinfoEntity stationinfo = gasStationinfoMapper.selectById(camid);

		GasStationinfoEntity stationinfoPid = gasStationinfoMapper.selectById(stationinfo.getPid());

		GasOfflineCamEntity offlineCamEntity = gasOfflineCamService.getById(camid);
		if (TsBqUtils.isNotNull(connect)) {

			stationinfo.setIconSkin(GasConstants.ICON_SKIN_ON);
			stationinfo.setUpdateId("mqtt");
			stationinfo.setUpdateTime(date);
		} else {

			stationinfo.setIconSkin(GasConstants.ICON_SKIN_OFF);
			stationinfo.setUpdateId("mqtt");
			stationinfo.setUpdateTime(date);
		}

		gasStationinfoMapper.updateById(stationinfo);

		String iconSkin = stationinfo.getIconSkin();
		// 处理离线
		log.debug("gasOfflineCamService=状态：" + camid + ":" + TsBqUtils.isNotNull(offlineCamEntity) + ":" + iconSkin);
		String pid = stationinfo.getPid();
		int status = -1;
		String errmsg = "";
		if (TsBqUtils.isNotNull(offlineCamEntity) && iconSkin.equals(GasConstants.ICON_SKIN_OFF)) {
			// 已离线、未恢复
			log.debug("gasOfflineCamService=已离线、未恢复：" + camid);
		} else if (TsBqUtils.isNotNull(offlineCamEntity) && !iconSkin.equals(GasConstants.ICON_SKIN_OFF)) {
			status = 1;
			errmsg = "摄像机恢复在线";
			// 已离线、恢复在线
			log.debug("gasOfflineCamService=已离线、恢复在线：" + camid);
			offlineCamEntity.setRecoverTime(connect);
			offlineCamEntity.setId(camid + "_" + TsBqUtils.getUUID());
			gasOfflineCamService.save(offlineCamEntity);
			gasOfflineCamService.realDelete(camid);
		} else if (TsBqUtils.isNull(offlineCamEntity) && iconSkin.equals(GasConstants.ICON_SKIN_OFF)) {
			status = 0;
			errmsg = "摄像机离线";
			// 新离线
			log.debug("gasOfflineCamService=新离线：" + camid);
			GasOfflineCamEntity gasOfflineCamEntity = new GasOfflineCamEntity();

			gasOfflineCamEntity.setId(camid);
			gasOfflineCamEntity.setTaxorgName(stationinfoPid.getTaxorgcode());
			gasOfflineCamEntity.setStationName(pid);
			gasOfflineCamEntity.setCamId(camid);
			gasOfflineCamEntity.setOfflineTime(disconnect);
			gasOfflineCamEntity.setDeleted(Constants.DATA_NOT_DELETED);
			gasOfflineCamEntity.setCreateTime(date);

			gasOfflineCamService.save(gasOfflineCamEntity);

		} else {
			log.debug("gasOfflineCamService=未知：" + camid);
		}

		int _status = status;
		String _errmsg = errmsg;
		// 写入省平台数据库
		SysParameterEntity parameterEntity106 = sysParameterService.getById("parameter106");
		if (TsBqUtils.isNotNull(parameterEntity106)) {
			String parameter106 = parameterEntity106.getParameter();
			log.info("parameter106参数值：" + parameter106);
			if ("Y".equals(parameter106)) {
				log.info("开始进行推送省平台！");
				try {
					pushProvince(camid, date, _status, pid);
				} catch (Exception e) {
					log.error("写入GasCamQuality表CamStreamState异常:" + e.getMessage());
				}
			}
		}

		SysParameterEntity parameterEntity102 = sysParameterService.getById("parameter102");

		if (TsBqUtils.isNotNull(parameterEntity102)) {
			String parameter102 = parameterEntity102.getParameter();
			if ("Y".equals(parameter102) && status != -1) {
				log.info("开始进行推送正南平台！");
				try {
					pushZN(stationinfoPid, stationinfo, _status, _errmsg);
				} catch (Exception e) {
					log.error("写入gas_camera_clog异常:" + e.getMessage());
				}
			}
		}
	}

	private void pushZN(GasStationinfoEntity stationinfoPid, GasStationinfoEntity stationinfo, int _status,
			String _errmsg) {
		DynamicDataSourceContextHolder.clear();
		ZnGasStation znGasStation = znGasStationMapper.selectById(stationinfoPid.getThirdPartyId());
		ZnGasCamera znGasCamera = znGasCameraMapper.selectById(stationinfo.getThirdPartyId());

		if (znGasStation.getIsNormal() == 1 && znGasStation.getIsValid() == 1) {
			String sql = "INSERT INTO gas_camera_clog "
					+ "(id, stationId, cameraId, indexCode, status, createTime, errmsg) " + " VALUES ('"
					+ TsBqUtils.getUUID() + "', " + stationinfoPid.getThirdPartyId() + ", "
					+ stationinfo.getThirdPartyId() + ", 'indexCode', " + _status + ", SYSDATE(), '" + _errmsg + "')";
			log.debug("执行sql:" + sql);

			znGasCamera.setOnline(_status);
			znGasCameraMapper.updateById(znGasCamera);

			gasDetectionSqlMapper.gasDetectionInsertInto(sql);
		} else {
			log.debug("加油站数据不传IsNormalIsValid:" + znGasStation.getIsNormal() + znGasStation.getIsValid());

		}
	}

	private void pushProvince(String camid, Date date, int _status, String pid) {
		DynamicDataSourceContextHolder.clear();
		LambdaQueryWrapper<ProvinceGasCamQualityEntity> provinceQueryWrapper = Wrappers.lambdaQuery();
		provinceQueryWrapper.eq(ProvinceGasCamQualityEntity::getCamId, camid);
		List<ProvinceGasCamQualityEntity> listProvinceGasCamQuality = provinceGasCamQualityMapper
				.selectList(provinceQueryWrapper);
		String stateStr = "";
		if (TsBqUtils.isNotNull(listProvinceGasCamQuality)) {
			ProvinceGasCamQualityEntity provinceGasCamQualityEntity = listProvinceGasCamQuality.get(0);
			provinceGasCamQualityEntity.setUpdateTime(date);
			if (_status == 1) {
				// 能取到流
				stateStr = "能取到流";
				provinceGasCamQualityEntity.setCamStreamState("1");
			} else {
				// 不能取到流
				stateStr = "不能取到流";
				provinceGasCamQualityEntity.setCamStreamState("0");
			}
			log.info("新增GasCamQuality表CamStreamState摄像头:" + camid + ",状态：" + stateStr);
			provinceGasCamQualityMapper.updateById(provinceGasCamQualityEntity);

		} else {
			// 新增
			ProvinceGasCamQualityEntity provinceGasCamQualityEntity = new ProvinceGasCamQualityEntity();
			provinceGasCamQualityEntity.setCamId(camid);
			provinceGasCamQualityEntity.setStationinfoId(pid);
			if (_status == 1) {
				// 能取到流
				stateStr = "能取到流";
				provinceGasCamQualityEntity.setCamStreamState("1");
			} else {
				// 不能取到流
				stateStr = "不能取到流";
				provinceGasCamQualityEntity.setCamStreamState("0");
			}
			provinceGasCamQualityEntity.setDeleted(Constants.DATA_NOT_DELETED);
			provinceGasCamQualityEntity.setCreateTime(date);
			log.info("新增GasCamQuality表CamStreamState摄像头:" + camid + ",状态：" + stateStr);
			provinceGasCamQualityMapper.insert(provinceGasCamQualityEntity);

		}
	}

	private void nrOfflineCamSaveAndUpdate(NrCamonlinetimeEntity entity) {

		Date date = new Date();
		String camid = entity.getMessageCamid();
		String connect = entity.getMessageConnect(); // 重新连接时间
		String disconnect = entity.getMessageDisconnect(); // 离线时间

		GasStationinfoEntity stationinfo = gasStationinfoMapper.selectById(camid);

		GasStationinfoEntity stationinfoPid = gasStationinfoMapper.selectById(stationinfo.getPid());

		NrOfflineCamEntity offlineCamEntity = nrOfflineCamService.getById(camid);
		// 更新摄像头状态
		if (TsBqUtils.isNotNull(connect)) {

			stationinfo.setIconSkin(GasConstants.ICON_SKIN_ON);
			stationinfo.setUpdateId("mqtt");
			stationinfo.setUpdateTime(date);
		} else {

			stationinfo.setIconSkin(GasConstants.ICON_SKIN_OFF);
			stationinfo.setUpdateId("mqtt");
			stationinfo.setUpdateTime(date);
		}

		gasStationinfoMapper.updateById(stationinfo);

		String iconSkin = stationinfo.getIconSkin();
		// 处理离线
		log.debug("nrOfflineCamService=状态：" + camid + ":" + TsBqUtils.isNotNull(offlineCamEntity) + ":" + iconSkin);
		int status = -1;
		String errmsg = "";
		if (TsBqUtils.isNotNull(offlineCamEntity) && iconSkin.equals(GasConstants.ICON_SKIN_OFF)) {
			// 已离线、未恢复
			log.debug("nrOfflineCamService=已离线、未恢复：" + camid);
		} else if (TsBqUtils.isNotNull(offlineCamEntity) && !iconSkin.equals(GasConstants.ICON_SKIN_OFF)) {
			status = 1;
			errmsg = "摄像机恢复在线";
			// 已离线、恢复在线
			log.debug("nrOfflineCamService=已离线、恢复在线：" + camid);
			offlineCamEntity.setOfflineTime(disconnect);
			offlineCamEntity.setRecoverTime(connect);
			offlineCamEntity.setId(camid + "_" + TsBqUtils.getUUID());
			nrOfflineCamService.save(offlineCamEntity);
			nrOfflineCamService.realDelete(camid);

		} else if (TsBqUtils.isNull(offlineCamEntity) && iconSkin.equals(GasConstants.ICON_SKIN_OFF)) {
			status = 0;
			errmsg = "摄像机离线";
			// 新离线
			log.debug("nrOfflineCamService=新离线：" + camid);
			NrOfflineCamEntity nrOfflineCamEntity = new NrOfflineCamEntity();
			String pid = stationinfo.getPid();
			nrOfflineCamEntity.setId(camid);
			nrOfflineCamEntity.setTaxorgName(stationinfoPid.getTaxorgcode());
			nrOfflineCamEntity.setStationName(pid);
			nrOfflineCamEntity.setCamId(camid);
			nrOfflineCamEntity.setOfflineTime(disconnect);
			nrOfflineCamEntity.setDeleted(Constants.DATA_NOT_DELETED);
			nrOfflineCamEntity.setCreateTime(date);

			nrOfflineCamService.save(nrOfflineCamEntity);

		} else {
			log.debug("nrOfflineCamService=未知：" + camid);
		}

		SysParameterEntity parameterEntity102 = sysParameterService.getById("parameter102");

		try {
			if (TsBqUtils.isNotNull(parameterEntity102)) {
				String parameter102 = parameterEntity102.getParameter();
				if ("Y".equals(parameter102) && status != -1) {

					ZnGasStation znGasStation = znGasStationMapper.selectById(stationinfoPid.getThirdPartyId());
					ZnGasCamera znGasCamera = znGasCameraMapper.selectById(stationinfo.getThirdPartyId());

					if (znGasStation.getIsNormal() == 1 && znGasStation.getIsValid() == 1) {
						String sql = "INSERT INTO gas_camera_clog "
								+ "(id, stationId, cameraId, indexCode, status, createTime, errmsg) " + " VALUES ('"
								+ TsBqUtils.getUUID() + "', " + stationinfoPid.getThirdPartyId() + ", "
								+ stationinfo.getThirdPartyId() + ", 'indexCode', " + status + ", SYSDATE(), '" + errmsg
								+ "')";
						log.debug("执行sql:" + sql);

						znGasCamera.setOnline(status);
						znGasCameraMapper.updateById(znGasCamera);

						gasDetectionSqlMapper.gasDetectionInsertInto(sql);
					} else {
						log.debug("加油站数据不传IsNormalIsValid:" + znGasStation.getIsNormal() + znGasStation.getIsValid());

					}
				}
			}
		} catch (Exception e) {
			log.error("写入nr_camera_clog异常:" + e.getMessage());
		}

	}

	@Override
	public void realDelete(String id) {
		gasStaytimeMapper.realDelete(id);
	}

	public static void main(String[] args) {
		String camid = String.valueOf("");
		System.out.println(camid);
	}
}